<template>
  <view class="profile-container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <!-- 头像选择按钮 -->
        <button
          class="avatar-button"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
        >
          <image
            :src="userInfo.avatar_url || '/static/default-avatar.png'"
            class="avatar"
            mode="aspectFill"
          />
          <view class="avatar-overlay">
            <text class="avatar-tip">点击更换头像</text>
          </view>
        </button>

        <view class="user-details">
          <!-- 昵称输入框 -->
          <input
            type="nickname"
            v-model="userInfo.nickname"
            class="nickname-input"
            placeholder="请输入昵称"
            @blur="updateNickname"
          />
          <text class="phone">{{ userInfo.phone_number || '未绑定手机' }}</text>
          <text class="wechat">{{ userInfo.wechat_id || '未设置微信号' }}</text>
          <view class="status-badge" :class="getStatusClass(userInfo.status)">
            {{ getStatusText(userInfo.status) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-card">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ userInfo.publishing_credits || 0 }}</text>
          <text class="stat-label">发布次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userInfo.chat_credits || 0 }}</text>
          <text class="stat-label">聊天次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userInfo.contact_view_credits || 0 }}</text>
          <text class="stat-label">查看次数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userInfo.local_service_credits || 0 }}</text>
          <text class="stat-label">本地服务</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ userInfo.statistics?.total_listings || 0 }}</text>
          <text class="stat-label">累计发布</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="goToMyListings">
        <view class="menu-icon">📋</view>
        <text class="menu-title">我的发布</text>
        <text class="menu-desc">管理我发布的信息</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToPublish">
        <view class="menu-icon">➕</view>
        <text class="menu-title">发布信息</text>
        <text class="menu-desc">发布新的转让信息</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToPackages">
        <view class="menu-icon">💎</view>
        <text class="menu-title">购买套餐</text>
        <text class="menu-desc">增加发布次数</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="goToInvite">
        <view class="menu-icon">👥</view>
        <text class="menu-title">邀请好友</text>
        <text class="menu-desc">邀请好友获得奖励</text>
        <text class="menu-arrow">></text>
      </view>

      <view class="menu-item" @click="shareApp">
        <view class="menu-icon">📤</view>
        <text class="menu-title">分享应用</text>
        <text class="menu-desc">分享给更多朋友</text>
        <text class="menu-arrow">></text>
      </view>
    </view>

    <!-- 公众号关注入口 -->
    <view class="menu-section highlight-section">
      <view class="menu-item" @click="goToOfficialFollow">
        <view class="menu-icon">📱</view>
        <text class="menu-title">关注公众号</text>
        <text class="menu-desc">接收消息推送提醒</text>
        <view class="recommend-badge">推荐</view>
        <text class="menu-arrow">></text>
      </view>
    </view>

    <!-- 设置菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="updatePhone">
        <view class="menu-icon">📱</view>
        <text class="menu-title">修改手机号</text>
        <text class="menu-desc">设置联系手机号</text>
        <text class="menu-arrow">></text>
      </view>

      <view class="menu-item" @click="updateWechat">
        <view class="menu-icon">💬</view>
        <text class="menu-title">设置微信号</text>
        <text class="menu-desc">设置微信联系方式</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @click="contactService">
        <view class="menu-icon">📞</view>
        <text class="menu-title">联系客服</text>
        <text class="menu-desc">遇到问题联系我们</text>
        <text class="menu-arrow">></text>
      </view>

      <view class="menu-item" @click="logout">
        <view class="menu-icon">🚪</view>
        <text class="menu-title">退出登录</text>
        <text class="menu-desc">安全退出当前账号</text>
        <text class="menu-arrow">></text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { userAPI, authAPI, utils } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const userInfo = ref({})
const isLoading = ref(false)

// 生命周期
onShow(() => {
  loadUserInfo()
})

// 方法定义
const loadUserInfo = async () => {
  try {
    isLoading.value = true
    
    const response = await userAPI.getCurrentUser()
    
    if (response.success) {
      userInfo.value = response.data
    } else {
      utils.handleError(new Error(response.message), '获取用户信息失败')
    }
    
  } catch (error) {
    utils.handleError(error, '获取用户信息失败')
  } finally {
    isLoading.value = false
  }
}

const getUserProfile = () => {
  uni.getUserProfile({
    desc: '用于完善用户资料',
    success: async (res) => {
      try {
        const { nickName, avatarUrl } = res.userInfo
        
        const response = await userAPI.updateUser({
          nickname: nickName,
          avatar_url: avatarUrl
        })
        
        if (response.success) {
          uni.showToast({
            title: '授权成功',
            icon: 'success'
          })
          
          // 更新本地用户信息
          userInfo.value.nickname = nickName
          userInfo.value.avatar_url = avatarUrl
        } else {
          utils.handleError(new Error(response.message), '更新用户信息失败')
        }
        
      } catch (error) {
        utils.handleError(error, '更新用户信息失败')
      }
    },
    fail: () => {
      uni.showToast({
        title: '授权失败',
        icon: 'none'
      })
    }
  })
}

const goToMyListings = () => {
  uni.navigateTo({
    url: '/pages/user/my-listings'
  })
}

const goToPublish = async () => {
  const hasCredit = await CreditChecker.checkPublishingCredit({
    fromPage: '/pages/listings/publish',
    action: '发布信息'
  })
  if (!hasCredit) {
    return
  }
  uni.navigateTo({
    url: '/pages/listings/publish'
  })
}

const goToPackages = () => {
  uni.navigateTo({
    url: '/pages/packages/packages'
  })
}

const goToInvite = () => {
  uni.navigateTo({
    url: '/pages/invite/invite'
  })
}

const shareApp = () => {
  // 跳转到邀请页面，让用户通过邀请页面进行分享
  uni.navigateTo({
    url: '/pages/invite/invite'
  })
}

const goToOfficialFollow = () => {
  uni.navigateTo({
    url: '/pages/official-account/follow'
  })
}

const updatePhone = () => {
  uni.showModal({
    title: '修改手机号',
    editable: true,
    placeholderText: '请输入手机号',
    success: async (res) => {
      if (res.confirm && res.content) {
        try {
          const response = await userAPI.updateUser({
            phone_number: res.content
          })

          if (response.success) {
            uni.showToast({
              title: '修改成功',
              icon: 'success'
            })

            userInfo.value.phone_number = res.content
          } else {
            utils.handleError(new Error(response.message), '修改失败')
          }

        } catch (error) {
          utils.handleError(error, '修改失败')
        }
      }
    }
  })
}

const updateWechat = () => {
  uni.showModal({
    title: '设置微信号',
    content: '请输入您的微信号',
    editable: true,
    placeholderText: '请输入微信号（如：wxid_xxx）',
    success: async (res) => {
      if (res.confirm && res.content) {
        // 简单验证微信号格式
        const wechatId = res.content.trim()
        if (wechatId.length < 3) {
          uni.showToast({
            title: '微信号格式不正确',
            icon: 'none'
          })
          return
        }

        try {
          const response = await userAPI.updateUser({
            wechat_id: wechatId
          })

          if (response.success) {
            uni.showToast({
              title: '设置成功',
              icon: 'success'
            })

            userInfo.value.wechat_id = wechatId
          } else {
            utils.handleError(new Error(response.message), '设置失败')
          }

        } catch (error) {
          utils.handleError(error, '设置失败')
        }
      }
    }
  })
}

const contactService = () => {
  uni.showModal({
    title: '联系客服',
    content: '客服微信：service123\n客服电话：400-123-4567',
    showCancel: false
  })
}

const logout = () => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await authAPI.logout()
        } catch (error) {
          console.log('登出接口调用失败，但继续清除本地数据')
        }
        
        // 清除本地数据
        utils.clearAuth()
        
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    }
  })
}

// 工具方法
const getStatusClass = (status) => {
  return status === 'active' ? 'status-active' : 'status-inactive'
}

const getStatusText = (status) => {
  return status === 'active' ? '已激活' : '未激活'
}

/**
 * 处理用户选择头像
 */
const onChooseAvatar = async (e) => {
  try {
    const avatarUrl = e.detail.avatarUrl
    console.log('选择的头像临时路径:', avatarUrl)

    // 显示上传中提示
    uni.showLoading({
      title: '上传头像中...'
    })

    try {
      // 上传头像到服务器
      const uploadResult = await userAPI.uploadAvatar(avatarUrl)

      if (uploadResult.success) {
        // 更新本地用户信息
        userInfo.value.avatar_url = uploadResult.data.url
        userInfo.value.avatar = uploadResult.data.url
        uni.setStorageSync('userInfo', userInfo.value)

        uni.hideLoading()
        uni.showToast({
          title: '头像上传成功',
          icon: 'success'
        })
      } else {
        throw new Error(uploadResult.message || '上传失败')
      }
    } catch (uploadError) {
      uni.hideLoading()
      console.error('上传头像失败:', uploadError)
      uni.showToast({
        title: '上传头像失败',
        icon: 'none'
      })
    }

  } catch (error) {
    uni.hideLoading()
    console.error('选择头像失败:', error)
    uni.showToast({
      title: '选择头像失败',
      icon: 'none'
    })
  }
}

/**
 * 更新昵称
 */
const updateNickname = async () => {
  try {
    const nickname = userInfo.value.nickname?.trim()
    if (!nickname) {
      uni.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
      return
    }

    // 更新用户信息
    const result = await userAPI.updateUser({
      nickname: nickname
    })

    if (result.success) {
      // 更新本地存储
      uni.setStorageSync('userInfo', userInfo.value)
      uni.showToast({
        title: '昵称更新成功',
        icon: 'success'
      })
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新昵称失败:', error)
    uni.showToast({
      title: '更新昵称失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.user-card {
  background: white;
  border-radius: 12rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar-button {
  position: relative;
  width: 120rpx;
  height: 120rpx;
  margin-right: 30rpx;
  padding: 0;
  border: none;
  background: transparent;
  border-radius: 60rpx;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 60rpx;
  background: #f0f0f0;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  text-align: center;
  padding: 4rpx 0;
  font-size: 20rpx;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-button:active .avatar-overlay {
  opacity: 1;
}

.avatar-tip {
  font-size: 20rpx;
  color: white;
}

.user-details {
  flex: 1;
}

.nickname-input {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  border: none;
  background: transparent;
  padding: 8rpx 0;
  border-bottom: 2rpx solid transparent;
  transition: border-color 0.3s ease;
}

.nickname-input:focus {
  border-bottom-color: #22c55e;
}

.nickname-input::placeholder {
  color: #999;
  font-weight: normal;
}

.phone {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.wechat {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.status-badge {
  display: inline-block;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;
}

.status-active {
  background: #22c55e;
}

.status-inactive {
  background: #f59e0b;
}

.auth-btn {
  width: 100%;
  height: 80rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.stats-card {
  background: white;
  border-radius: 12rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 20rpx;
}

.stat-item {
  text-align: center;
  padding: 20rpx 15rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.stat-item:last-child {
  grid-column: 2 / 3;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #22c55e;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 22rpx;
  color: #666;
  line-height: 1.2;
}

.menu-section {
  background: white;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 30rpx;
  width: 60rpx;
  text-align: center;
}

.menu-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 5rpx;
}

.menu-desc {
  font-size: 24rpx;
  color: #999;
  flex: 1;
  margin-left: 20rpx;
}

.menu-arrow {
  font-size: 28rpx;
  color: #ccc;
  margin-left: auto;
}

.menu-item:active {
  background: #f9f9f9;
}

/* 公众号关注高亮区域 */
.highlight-section {
  border: 2rpx solid #22c55e;
  position: relative;
  overflow: visible;
}

.highlight-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(34, 197, 94, 0.05), rgba(34, 197, 94, 0.02));
  border-radius: 12rpx;
  pointer-events: none;
}

.recommend-badge {
  padding: 6rpx 16rpx;
  background: linear-gradient(135deg, #22c55e, #16a34a);
  color: white;
  font-size: 22rpx;
  border-radius: 20rpx;
  margin-left: 15rpx;
}
</style>
